<template>
  <div class="achievements-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-select
              v-model="indicatorFilter"
              placeholder="指标点筛选"
              clearable
              @change="handleSearch"
              style="width: 200px"
            >
              <el-option
                v-for="indicator in indicators"
                :key="indicator.id"
                :label="indicator.indicatorName"
                :value="indicator.id"
              />
            </el-select>
            
            <el-select
              v-model="evaluationYearFilter"
              placeholder="评价年份筛选"
              clearable
              @change="handleSearch"
              style="width: 120px"
            >
              <el-option
                v-for="year in evaluationYears"
                :key="year"
                :label="year"
                :value="year"
              />
            </el-select>
            
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </div>
          
          <el-button
            type="primary"
            :icon="Plus"
            @click="handleAdd"
            v-if="userStore.isAdmin"
          >
            新增达成度
          </el-button>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="achievements"
        border
        style="width: 100%"
      >
        <el-table-column label="指标点" min-width="200">
          <template #default="{ row }">
            {{ getIndicatorName(row.indicatorId) }}
          </template>
        </el-table-column>
        
        <el-table-column prop="directEvaluation" label="直接评价" width="120">
          <template #default="{ row }">
            {{ row.directEvaluation }}
          </template>
        </el-table-column>
        
        <el-table-column prop="graduateSelfEval" label="毕业生自评" width="120">
          <template #default="{ row }">
            {{ row.graduateSelfEval }}
          </template>
        </el-table-column>
        
        <el-table-column prop="internshipEval" label="实习单位评价" width="120">
          <template #default="{ row }">
            {{ row.internshipEval }}
          </template>
        </el-table-column>
        
        <el-table-column prop="teacherEval" label="教师评价" width="120">
          <template #default="{ row }">
            {{ row.teacherEval }}
          </template>
        </el-table-column>
        
        <el-table-column prop="comprehensiveScore" label="综合评价值" width="120">
          <template #default="{ row }">
            {{ row.comprehensiveScore }}
          </template>
        </el-table-column>
        
        <el-table-column prop="isAchieved" label="是否达成" width="100">
          <template #default="{ row }">
            <el-tag :type="row.isAchieved ? 'success' : 'danger'">
              {{ row.isAchieved ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="evaluationYear" label="评价年份" width="100" />
        
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        
        <el-table-column prop="updateTime" label="更新时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.updateTime) }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              link
              :icon="Edit"
              @click="handleEdit(row)"
              v-if="userStore.isAdmin"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              link
              :icon="Delete"
              @click="handleDelete(row)"
              v-if="userStore.isAdmin"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 达成度表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增达成度' : '编辑达成度'"
      width="600px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="指标点" prop="indicatorId">
          <el-select
            v-model="form.indicatorId"
            placeholder="请选择指标点"
            style="width: 100%"
          >
            <el-option
              v-for="indicator in indicators"
              :key="indicator.id"
              :label="indicator.indicatorName"
              :value="indicator.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="直接评价" prop="directEvaluation">
          <el-input-number
            v-model="form.directEvaluation"
            :min="0"
            :max="1"
            :precision="2"
            :step="0.1"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="毕业生自评" prop="graduateSelfEval">
          <el-input-number
            v-model="form.graduateSelfEval"
            :min="0"
            :max="1"
            :precision="2"
            :step="0.1"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="实习单位评价" prop="internshipEval">
          <el-input-number
            v-model="form.internshipEval"
            :min="0"
            :max="1"
            :precision="2"
            :step="0.1"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="教师评价" prop="teacherEval">
          <el-input-number
            v-model="form.teacherEval"
            :min="0"
            :max="1"
            :precision="2"
            :step="0.1"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="综合评价值" prop="comprehensiveScore">
          <el-input-number
            v-model="form.comprehensiveScore"
            :min="0"
            :max="1"
            :precision="2"
            :step="0.1"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="是否达成" prop="isAchieved">
          <el-switch
            v-model="form.isAchieved"
            active-text="是"
            inactive-text="否"
          />
        </el-form-item>
        
        <el-form-item label="评价年份" prop="evaluationYear">
          <el-select
            v-model="form.evaluationYear"
            placeholder="请选择评价年份"
            style="width: 100%"
          >
            <el-option
              v-for="year in evaluationYears"
              :key="year"
              :label="year"
              :value="year"
            />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useUserStore } from '../store'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import request from '../api/request'

const userStore = useUserStore()
const loading = ref(false)
const submitting = ref(false)
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)
const indicatorFilter = ref('')
const evaluationYearFilter = ref('')
const achievements = ref([])
const indicators = ref([])

// 生成评价年份选项（当前年份前后5年）
const currentYear = new Date().getFullYear()
const evaluationYears = Array.from({ length: 11 }, (_, i) => currentYear - 5 + i)

const form = reactive({
  id: null,
  indicatorId: null,
  directEvaluation: 0,
  graduateSelfEval: 0,
  internshipEval: 0,
  teacherEval: 0,
  comprehensiveScore: 0,
  isAchieved: false,
  evaluationYear: null
})

const rules = {
  indicatorId: [
    { required: true, message: '请选择指标点', trigger: 'change' }
  ],
  directEvaluation: [
    { required: true, message: '请输入直接评价', trigger: 'blur' }
  ],
  graduateSelfEval: [
    { required: true, message: '请输入毕业生自评', trigger: 'blur' }
  ],
  internshipEval: [
    { required: true, message: '请输入实习单位评价', trigger: 'blur' }
  ],
  teacherEval: [
    { required: true, message: '请输入教师评价', trigger: 'blur' }
  ],
  comprehensiveScore: [
    { required: true, message: '请输入综合评价值', trigger: 'blur' }
  ],
  evaluationYear: [
    { required: true, message: '请选择评价年份', trigger: 'change' }
  ]
}

const fetchAchievements = async () => {
  try {
    loading.value = true
    const res = await request.get('/api/graduation-requirement-achievements', {
      params: {
        indicatorId: indicatorFilter.value,
        evaluationYear: evaluationYearFilter.value
      }
    })
    achievements.value = res.data
  } catch (error) {
    console.error('获取达成度列表失败:', error)
  } finally {
    loading.value = false
  }
}

const fetchIndicators = async () => {
  try {
    const res = await request.get('/api/indicators')
    indicators.value = res.data
  } catch (error) {
    console.error('获取指标点列表失败:', error)
  }
}

const handleSearch = () => {
  fetchAchievements()
}

const resetSearch = () => {
  indicatorFilter.value = ''
  evaluationYearFilter.value = ''
  fetchAchievements()
}

const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(form, {
    id: null,
    indicatorId: null,
    directEvaluation: 0,
    graduateSelfEval: 0,
    internshipEval: 0,
    teacherEval: 0,
    comprehensiveScore: 0,
    isAchieved: false,
    evaluationYear: null
  })
}

const handleAdd = () => {
  dialogType.value = 'add'
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.assign(form, {
    id: row.id,
    indicatorId: row.indicatorId,
    directEvaluation: row.directEvaluation,
    graduateSelfEval: row.graduateSelfEval,
    internshipEval: row.internshipEval,
    teacherEval: row.teacherEval,
    comprehensiveScore: row.comprehensiveScore,
    isAchieved: row.isAchieved,
    evaluationYear: row.evaluationYear
  })
  dialogVisible.value = true
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该达成度记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await request.delete(`/api/graduation-requirement-achievements/${row.id}`)
    ElMessage.success('删除成功')
    fetchAchievements()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
    }
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    if (dialogType.value === 'add') {
      await request.post('/api/graduation-requirement-achievements', form)
      ElMessage.success('新增成功')
    } else {
      await request.put(`/api/graduation-requirement-achievements/${form.id}`, form)
      ElMessage.success('编辑成功')
    }
    
    dialogVisible.value = false
    fetchAchievements()
  } catch (error) {
    console.error('提交失败:', error)
  } finally {
    submitting.value = false
  }
}

const getIndicatorName = (indicatorId) => {
  const indicator = indicators.value.find(i => i.id === indicatorId)
  return indicator ? indicator.indicatorName : ''
}

const formatDateTime = (datetime) => {
  if (!datetime) return ''
  return new Date(datetime).toLocaleString()
}

onMounted(async () => {
  await Promise.all([
    fetchAchievements(),
    fetchIndicators()
  ])
})
</script>

<style scoped>
.achievements-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  gap: 10px;
}
</style> 